package data

import (
	"crypto/sha1"
	_ "database/sql"
	_ "errors"
	"fmt"
	_ "gitchina/kly_service/util"
	"strconv"
	"time"

	"github.com/astaxie/beego/orm"
	_ "github.com/go-sql-driver/mysql"
)

var pay_passwd_salt = `@*%#@!@IL;lJo49M`

type PayRepo struct {
	o orm.Ormer
}

type WalletDto struct {
	Id       int     `orm:"pk;auto;column(id)"`
	MemberId int     `orm:"column(member_id)"`
	Pwd      string  `orm:"column(pay_pwd)"`
	Balance  float32 `orm:"column(balance)"`
	Balance2 string  `orm:"column(balance2)"`
}

type WalletDetailDto struct {
	Id         int     `orm:"pk;auto;column(id)"`
	MemberId   int     `orm:"column(member_id)"`
	FlowId     int64   `orm:"column(flow_id)"`
	Amount     float32 `orm:"column(amount)"`
	Balance    float32 `orm:"column(balance)"`
	Balance2   string  `orm:"column(balance2)"`
	TypeId     int     `orm:"column(type_id)"`
	Remark     string  `orm:"column(remark)"`
	CreateTime string  `orm:"column(create_time)"`
}

type PaymentDto struct {
	Id              int       `orm:"pk;auto;column(id)"`
	FlowId          int64     `orm:"column(flow_id)"`
	MemberId        int       `orm:"column(member_id)"`
	WaybillId       int       `orm:"column(waybill_id)"`
	BillAmount      float32   `orm:"column(bill_amount)"`
	InvoiceAmount   float32   `orm:"column(invoice_amount)"`
	InsuranceAmount float32   `orm:"column(insurance_amount)"`
	DepositAmount   float32   `orm:"column(deposit_amount)"`
	TotalAmount     float32   `orm:"column(total_amount)"`
	TypeId          int       `orm:"column(type_id)"`
	PayFor          int       `orm:column(pay_for)`
	CardId          int       `orm:"column(card_id)"`
	Remark          string    `orm:"column(remark)"`
	State           int       `orm:"column(state)"`
	CreateTime      time.Time `orm:"create_time"`
}

type TransFlowDto struct {
	Id         int64     `orm:"pk;auto;column(id)"`
	MemberId   int       `orm:"column(member_id)"`
	TransNo    string    `orm:"column(trans_no)"`
	Amount     float32   `orm:"column(amount)"`
	State      int       `orm:"column(state)"`
	TypeId     int       `orm:"column(type_id)"`
	Remark     string    `orm:"column(remark)"`
	CreateTime time.Time `orm:"column(create_time)"`
}

type BankDetailDto struct {
	Id         int     `orm:"pk;auto;column(id)"`
	MemberId   int     `orm:"column(member_id)"`
	FlowId     int64   `orm:"column(flow_id)"`
	Amount     float32 `orm:"column(amount)"`
	BindId     int     `orm:"column(bind_id)"`
	TypeId     int     `orm:"column(type_id)"`
	Remark     string  `orm:"column(remark)"`
	CreateTime string  `orm:"column(create_time)"`
}

type PlatformBalanceDto struct {
	Id       int     `orm:"pk;column(id)"`
	Balance  float32 `orm:"column(balance)"`
	Balance2 string  `orm:"column(balance2)"`
}

type PlatformDetailDto struct {
	Id        int     `orm:"pk;auto;column(id)"`
	FlowId    int64   `orm:"column(flow_id)"`
	BalanceId int     `orm:"column(balance_id)"`
	Amount    float32 `orm:"column(amount)"`
	Balance   float32 `orm:"column(balance)"`
	Balance2  string  `orm:"column(balance2)"`
	TypeId    int     `orm:"column(type_id)"`
	Remark    string  `orm:"column(remark)"`
}

type BankCardDto struct {
	Id          int    `orm:"pk;auto;column(id)"`
	MemberId    int    `orm:"column(member_id)"`
	Name        string `orm:"column(name)"`
	Phone       string `orm:"column(phone)"`
	No          string `orm:"column(card_no)"`
	Type        int    `orm:"column(card_type)"`
	Province    string `orm:"column(province)"`
	City        string `orm:"column(city)"`
	BankId      int    `orm:"column(bank_id)"`
	BankName    string `orm:"column(bank_name)"`
	BindId      int    `orm:"column(bind_id)"`
	IDNO        string `orm:"column(id_no)"`
	ValidDate   string `orm:"column(valid_date)"`
	Cvv2        string `orm:"column(cvv2)"`
	State       int    `orm:"column(state)"`
	Params      string `orm:"column(params)"`
	Undecoded   string `orm:"column(undecoded)"`
	PartnerType int    `orm:"column(partner_type)"`
	PartnerID   string `orm:"column(partner_id)"`
}

type WithdrawDto struct {
	Id               int     `orm:"pk;auto;column(id)"`
	MemberId         int     `orm:"column(member_id)"`
	FlowId           int64   `orm:"column(flow_id)"`
	Amount           float32 `orm:"column(amount)"`
	AmountAfterRatio float32 `orm:"column(amount_after_ratio)"`
	Amount2          string  `orm:'column(amount2)'`
	CardId           int     `orm:"column(card_id)"`
	Phone            string  `orm:"column(phone)"`
	CardNo           string  `orm:"column(card_no)"`
	BankName         string  `orm:"column(bank_name)"`
	CardType         int     `orm:"column(card_type)"`
	Province         string  `orm:"column(province)"`
	City             string  `orm:"column(city)"`
	State            int     `orm:"column(state)"`
	Remark           string  `orm:"column(remark)"`
}

type WithdrawDetailDto struct {
	Amount           float32 `orm:"column(amount)"`
	AmountAfterRatio float32 `orm:"column(amount_after_ratio)"`
	CardNo           string  `orm:"column(card_no)"`
	State            int     `orm:"column(state)"`
	Phone            string  `orm:"column(phone)"`
	BankName         string  `orm:"column(card_name)"`
	CardType         int     `orm:"column(card_type)"`
	Province         string  `orm:"column(province)"`
	City             string  `orm:"column(city)"`
	Remark           string  `orm:"column(remark)"`
	CreateTime       string  `orm:"column(create_time)"`
}

type RefundDto struct {
	Id         int       `orm:"pk;auto;column(id)"`
	FlowId     int64     `orm:"column(flow_id)"`
	MemberId   int       `orm:"column(member_id)"`
	WaybillId  int       `orm:"column(waybill_id)"`
	Amount     float32   `orm:"column(amount)"`
	RefundFor  int       `orm:column(refund_for)`
	Remark     string    `orm:"column(remark)"`
	State      int       `orm:"column(state)"`
	CreateTime time.Time `orm:"create_time"`
}

type RewardDto struct {
	Id        int     `orm:"pk;auto;column(id)"`
	FlowId    int64   `orm:"column(flow_id)"`
	MemberId  int     `orm:"column(member_id)"`
	WaybillId int     `orm:"column(waybill_id)"`
	Amount    float32 `orm:"column(amount)"`
}

type OilCardDto struct {
	Id       int     `orm:"pk;auto;column(id)"`
	MemberId int     `orm:"column(member_id)"`
	FlowId   int64   `orm:"column(flow_id)"`
	Amount   float32 `orm:"column(amount)"`
	Amount2  string  `orm:'column(amount2)'`
	CardNo   string  `orm:"column(card_no)"`
	CardType int     `orm:"column(card_type)"`
	State    int     `orm:"column(state)"`
	Remark   string  `orm:"column(remark)"`
}

type PayOfflineDto struct {
	Id               int    `orm:"pk;auto;column(id)"`
	MemberID         int    `orm:"column(member_id)"`
	WaybillID        int    `orm:"column(waybill_id)"`
	BankName         string `orm:"column(bank_name)"`
	BankCard         string `orm:"column(bank_card)"`
	InvoiceID        int    `orm:"column(invoice_id)"`
	InvoiceIssueCorp string `orm:"column(invoice_issue_corp)"`
	PayeeName        string `orm:"column(payee_name)"`
	PayeeIDCard      string `orm:"column(payee_idcard)"`
}

type QPayDto struct {
	ID        int    `orm:"pk;column(id)"`
	MemberID  int    `orm:"column(member_id)"`
	Amount    int    `orm:"column(amount)"`
	State     int    `orm:"column(state)"`
	Params    string `orm:"column(params)"`
	Undecoded string `orm:"column(undecoded)"`
}

func init() {
	orm.RegisterModel(new(PaymentDto),
		new(TransFlowDto),
		new(BankDetailDto),
		new(WalletDto),
		new(WalletDetailDto),
		new(PlatformBalanceDto),
		new(PlatformDetailDto),
		new(BankCardDto),
		new(WithdrawDto),
		new(RefundDto),
		new(RewardDto),
		new(OilCardDto),
		new(PayOfflineDto),
		new(QPayDto))
}

func (dto *PaymentDto) TableName() string {
	return "t_payment"
}

func (dto *TransFlowDto) TableName() string {
	return "t_trans_flow"
}

func (dto *BankDetailDto) TableName() string {
	return "t_bank_detail"
}

func (dto *WalletDto) TableName() string {
	return "m_wallet"
}

func (dto *WalletDetailDto) TableName() string {
	return "t_wallet_detail"
}

func (dto *PlatformBalanceDto) TableName() string {
	return "t_platform_balance"
}

func (dto *PlatformDetailDto) TableName() string {
	return "t_platform_detail"
}

func (dto *BankCardDto) TableName() string {
	return "t_bank_card"
}

func (dto *WithdrawDto) TableName() string {
	return "t_withdraw"
}

func (dto *RefundDto) TableName() string {
	return "t_refund"
}

func (dto *RewardDto) TableName() string {
	return "t_reward"
}

func (dto *OilCardDto) TableName() string {
	return "t_oilcard"
}

func (dto *PayOfflineDto) TableName() string {
	return "t_pay_offline"
}

func (dto *QPayDto) TableName() string {
	return "t_qpay"
}

func (repo PayRepo) AddWallet(w WalletDto) (alreadyCreated bool, err error) {
	var created bool
	if repo.o == nil {
		repo.o = orm.NewOrm()
	}
	w.Balance = 0
	if w.Pwd != "" {
		w.Pwd = fmt.Sprintf("%x", sha1.Sum([]byte(fmt.Sprintf("%s%s", w.Pwd, pay_passwd_salt))))
	}
	w.Balance2 = fmt.Sprintf("%x", sha1.Sum([]byte(fmt.Sprintf("%d%s", w.Balance, pay_passwd_salt))))

	if created, _, err = repo.o.ReadOrCreate(&w, "MemberId"); err == nil {
		if !created {
			alreadyCreated = true
		}
	}
	return
}

func (repo PayRepo) UpdateWalletPwd(memberId int, oldPwd, newPwd string) (bool, error) {
	o := orm.NewOrm()
	oldPwd = fmt.Sprintf("%x", sha1.Sum([]byte(fmt.Sprintf("%s%s", oldPwd, pay_passwd_salt))))
	newPwd = fmt.Sprintf("%x", sha1.Sum([]byte(fmt.Sprintf("%s%s", newPwd, pay_passwd_salt))))
	cnt, err := o.QueryTable("m_wallet").
		Filter("MemberId", memberId).
		Filter("Pwd", oldPwd).
		Update(orm.Params{"Pwd": newPwd})
	return cnt == 1, err
}

func (repo PayRepo) CheckPaid(waybillId, payFor int) (bool, error) {
	o := orm.NewOrm()
	cnt, err := o.QueryTable("t_payment").
		Filter("WaybillId", waybillId).
		Filter("PayFor", payFor).
		Filter("State", 1).
		Count()
	return cnt >= 1, err
}

func (repo *PayRepo) GetUnpaid(waybillId int) (dto PaymentDto, ok bool, err error) {
	var nums int64
	var list []PaymentDto
	o := orm.NewOrm()
	if nums, err = o.QueryTable("t_payment").
		Filter("WaybillId", waybillId).
		Filter("State", 0).
		OrderBy("-id").
		All(&list); err == nil {
		if ok = nums > 0; ok {
			dto = list[0]
		}
	}
	return
}

func (repo PayRepo) GetPaymentDetailByPayID(payID int) (PaymentDto, error) {
	var p PaymentDto

	o := orm.NewOrm()
	err := o.QueryTable("t_payment").
		Filter("Id", payID).
		One(&p)
	return p, err
}

func (repo PayRepo) GetPaymentDetailById(payId, memberId int) (dto PaymentDto, err error) {
	o := orm.NewOrm()
	err = o.QueryTable("t_payment").
		Filter("Id", payId).
		Filter("MemberId", memberId).
		One(&dto)
	return
}

func (repo PayRepo) GetPaymentDetailByIdWithAmount(payId int, amount float32) (dto PaymentDto, err error) {
	o := orm.NewOrm()
	err = o.QueryTable("t_payment").
		Filter("Id", payId).
		Filter("TotalAmount", amount).
		One(&dto)
	return
}

func (repo PayRepo) GetPaymentDetailByWaybillId(waybillId, payFor, state int) (dto PaymentDto, err error) {
	o := orm.NewOrm()
	err = o.QueryTable("t_payment").
		Filter("WaybillId", waybillId).
		Filter("State", state).
		Filter("PayFor", payFor).
		One(&dto)
	return
}

func (repo PayRepo) GetNotCompletePaymentToPost() (list []PaymentDto, err error) {
	o := orm.NewOrm()
	start := time.Now().Add(-(5*60*time.Second + 30*time.Second)).Format("2006-01-02 15:04:05")
	end := time.Now().Add(-30 * time.Second).Format("2006-01-02 15:04:05")
	_, err = o.QueryTable("t_payment").
		Filter("create_time__gte", start).
		Filter("create_time__lte", end).
		Filter("State", 0).
		All(&list)
	return
}

func (repo PayRepo) CheckSuccPaymentRecord(waybillId, payFor int) (bool, error) {
	o := orm.NewOrm()
	cnt, err := o.QueryTable("t_payment").
		Filter("WaybillId", waybillId).
		Filter("PayFor", payFor).
		Filter("State", 1).
		Count()
	return cnt == 1, err
}

func (repo PayRepo) CheckWalletNotToppedUp(memberId, typeId int, transNo string) (bool, error) {
	o := orm.NewOrm()
	cnt, err := o.QueryTable("t_trans_flow").
		Filter("MemberId", memberId).
		Filter("TransNo", transNo).
		Filter("TypeId", typeId).
		Filter("State", 1).
		Count()
	return cnt == 0, err
}

func (repo *PayRepo) AddOrUpdateBankCard(dto BankCardDto) (cardId int, err error) {
	var id int64
	o := orm.NewOrm()
	if dto.Id != 0 {
		if _, err = o.Update(&dto); err == nil {
			cardId = dto.Id
		}
	} else {
		if exists := o.QueryTable("t_bank_card").
			Filter("MemberId", dto.MemberId).
			Filter("No", dto.No).
			Filter("Type", dto.Type).
			Exist(); !exists {
			if id, err = o.Insert(&dto); err == nil {
				cardId = int(id)
			}
		}
	}
	return
}

func (repo *PayRepo) HasQPayCardBound(memberID int, no string) (bool, *BankCardDto) {
	var b BankCardDto
	o := orm.NewOrm()
	err := o.QueryTable("t_bank_card").
		Filter("MemberId", memberID).
		Filter("No", no).
		Filter("Type", 1).
		One(&b)
	return err == nil, &b
}

func (repo *PayRepo) GetQPayBankCard(memberID, cardID int) (*BankCardDto, error) {
	var b BankCardDto
	o := orm.NewOrm()
	err := o.QueryTable("t_bank_card").
		Filter("id", cardID).
		Filter("MemberId", memberID).
		One(&b)
	return &b, err
}

func (repo *PayRepo) AddQPayCard(card BankCardDto) (*BankCardDto, error) {
	var b *BankCardDto

	o := orm.NewOrm()
	_, err := o.Insert(&card)
	if err == nil {
		_, b = repo.HasQPayCardBound(card.MemberId, card.No)
	}
	return b, err
}

func (repo *PayRepo) SetQPayBankCardApplyOK(cardID int, params, undecoded string) error {
	o := orm.NewOrm()
	_, err := o.Raw(SQL_Wallet_Set_QPay_BankCard_Apply_OK, params, undecoded, cardID).Exec()
	return err
}

func (repo *PayRepo) UpdateQPayBankCardUndecoded(cardID int, undecoded string) error {
	o := orm.NewOrm()
	_, err := o.Raw(SQL_Wallet_Update_QPay_BankCard_Undecoded, undecoded, cardID).Exec()
	return err
}

func (repo *PayRepo) SetQPayBankCardConfirmOK(cardID int, partnerID, undecoded string) error {
	o := orm.NewOrm()
	_, err := o.Raw(SQL_Wallet_Set_QPay_BankCard_Confirm_OK, partnerID, undecoded, cardID).Exec()
	return err
}

func (repo *PayRepo) GetQPay(payID int) (bool, *QPayDto) {
	var q QPayDto

	o := orm.NewOrm()
	err := o.QueryTable("t_qpay").Filter("id", payID).One(&q)
	return err == nil, &q
}

func (repo *PayRepo) AddQPay(q *QPayDto) error {
	o := orm.NewOrm()
	_, err := o.Insert(q)
	return err
}

func (repo *PayRepo) SetQPayApplyOK(payID int, params, undecoded string) error {
	o := orm.NewOrm()
	_, err := o.Raw(SQL_QPay_Apply_OK, params, undecoded, payID).Exec()
	return err
}

func (repo *PayRepo) SetQPayConfirmOK(payID int, undecoded string) error {
	o := orm.NewOrm()
	_, err := o.Raw(SQL_QPay_Confirm_OK, undecoded, payID).Exec()
	return err
}

func (repo *PayRepo) UpdateQPayUndecoded(payID int, undecoded string) error {
	o := orm.NewOrm()
	_, err := o.Raw(SQL_QPay_Update_Undecoded, undecoded, payID).Exec()
	return err
}

func (repo *PayRepo) CheckCardBelongsToOwner(memberId, cardId int) (bool, error) {
	o := orm.NewOrm()
	cnt, err := o.QueryTable("t_bank_card").Filter("MemberId", memberId).Filter("Id", cardId).Count()
	return cnt == 1, err
}

func (repo *PayRepo) BeginTx() (err error) {
	repo.o = orm.NewOrm()
	if err = repo.o.Begin(); err != nil {
		repo.o.Rollback()
	}
	return
}

func (repo *PayRepo) EndTx(ok bool) (err error) {
	if ok {
		err = repo.o.Commit()
	} else {
		err = repo.o.Rollback()
	}
	return
}

func (repo *PayRepo) NewTransFlow(t TransFlowDto) (id int64, err error) {
	t.CreateTime, _ = time.Parse("2006-01-02 15:04:05", time.Now().Format("2006-01-02 15:04:05"))
	id, err = repo.o.Insert(&t)
	return
}

func (repo *PayRepo) NewPayment(p PaymentDto) (id int64, err error) {
	p.CreateTime, _ = time.Parse("2006-01-02 15:04:05", time.Now().Format("2006-01-02 15:04:05"))
	id, err = repo.o.Insert(&p)
	return
}

func (repo *PayRepo) NewRefund(r RefundDto) error {
	r.CreateTime, _ = time.Parse("2006-01-02 15:04:05", time.Now().Format("2006-01-02 15:04:05"))
	_, err := repo.o.Insert(&r)
	return err
}

func (repo PayRepo) CheckNotRefund(waybillId, refundFor int) (ok bool, err error) {
	var cnt int64
	o := orm.NewOrm()
	if cnt, err = o.QueryTable("t_refund").Filter("RefundFor", refundFor).Filter("WaybillId", waybillId).Count(); err == nil {
		ok = cnt == 0
	}
	return
}

func (repo PayRepo) GetRefundAmountByWaybillId(waybillId int) (amount float32, err error) {
	var refundDto RefundDto
	o := orm.NewOrm()
	if err = o.QueryTable("t_refund").Filter("WaybillId", waybillId).One(&refundDto); err == nil {
		amount = refundDto.Amount
	}
	return
}

func (repo *PayRepo) NewBankDetailRecord(b BankDetailDto) (err error) {
	b.CreateTime = time.Now().Format("2006-01-02 15:04:05")
	_, err = repo.o.Insert(&b)
	return
}

func (repo *PayRepo) UpdatePaymentState(payId int, payOk bool, remark string) (err error) {
	var nums int64
	state := 2
	if payOk {
		state = 1
	}
	nums, err = repo.o.QueryTable("t_payment").
		Filter("Id", payId).
		Filter("State", 0).
		Update(orm.Params{"State": state, "Remark": remark})
	if nums == 0 {
		if err != nil {
			err = fmt.Errorf("update id = %d, but no rows affected", payId)
		}
	}
	return
}

func (repo PayRepo) Cancel(payId int) (err error) {
	o := orm.NewOrm()
	_, err = o.QueryTable("t_payment").
		Filter("Id", payId).
		Update(orm.Params{"State": 3})
	return
}

func (repo *PayRepo) UpdateTransFlowState(flowId int64, payOk bool, remark string) (err error) {
	var nums int64
	state := 2
	if payOk {
		state = 1
	}
	nums, err = repo.o.QueryTable("t_trans_flow").
		Filter("Id", flowId).
		Filter("State", 0).
		Update(orm.Params{"State": state})
	if nums == 0 {
		if err != nil {
			err = fmt.Errorf("update id = %d, but no rows affected", flowId)
		}
	}
	return
}

func (repo *PayRepo) GetWallet(memberId int) (w WalletDto, err error) {
	if repo.o == nil {
		repo.o = orm.NewOrm()
	}
	err = repo.o.QueryTable("m_wallet").
		Filter("MemberId", memberId).
		One(&w)
	return
}

func (repo *PayRepo) GetWalletWithPwd(memberId int, pwd string) (w WalletDto, err error) {
	if repo.o == nil {
		repo.o = orm.NewOrm()
	}
	err = repo.o.QueryTable("m_wallet").
		Filter("MemberId", memberId).
		//Filter("Pwd", fmt.Sprintf("%x", sha1.Sum([]byte(fmt.Sprintf("%s%s", pwd, pay_passwd_salt))))).
		One(&w)
	return
}

func (repo *PayRepo) UpdateWalletBalance(w *WalletDto, oldBalance float32) error {
	oldBalance2 := w.Balance2
	w.Balance2 = fmt.Sprintf("%x", sha1.Sum([]byte(fmt.Sprintf("%d%s", w.Balance, pay_passwd_salt))))
	_, err := repo.o.QueryTable("m_wallet").
		Filter("MemberId", w.MemberId).
		Filter("Balance", oldBalance).
		Filter("Balance2", oldBalance2).
		Update(orm.Params{"Balance": w.Balance, "Balance2": w.Balance2})
	return err
}

func (repo *PayRepo) NewWalletDetailRecord(w WalletDetailDto) error {
	w.CreateTime = time.Now().Format("2006-01-02 15:04:05")
	_, err := repo.o.Insert(&w)
	return err
}

func (repo *PayRepo) GetPlatformBalances(ids []int) (p []PlatformBalanceDto, err error) {
	if repo.o == nil {
		repo.o = orm.NewOrm()
	}
	_, err = repo.o.QueryTable("t_platform_balance").Filter("Id__in", ids).OrderBy("Id").All(&p)
	return
}

func (repo *PayRepo) GetPlatformBalanceById(id int) (p PlatformBalanceDto, err error) {
	if repo.o == nil {
		repo.o = orm.NewOrm()
	}
	err = repo.o.QueryTable("t_platform_balance").Filter("id", id).One(&p)
	return
}

func (repo *PayRepo) AddAndUpdatePlatformBalance(p PlatformBalanceDto, flowId int64, amount float32, platformDetailTypeId int) (err error) {
	if repo.o == nil {
		repo.o = orm.NewOrm()
	}
	oldBalance := p.Balance
	p.Balance = p.Balance + amount
	if err = repo.UpdatePlatformBalance(&p, oldBalance); err == nil {
		err = repo.NewPlatformDetailRecord(PlatformDetailDto{
			FlowId:    flowId,
			BalanceId: p.Id,
			Amount:    amount,
			Balance:   p.Balance,
			Balance2:  p.Balance2,
			TypeId:    platformDetailTypeId,
		})
	}
	return
}

func (repo *PayRepo) UpdatePlatformBalance(p *PlatformBalanceDto, oldBalance float32) error {
	if repo.o == nil {
		repo.o = orm.NewOrm()
	}
	oldBalance2 := p.Balance2
	p.Balance2 = fmt.Sprintf("%x", sha1.Sum([]byte(fmt.Sprintf("%d%s", p.Balance, pay_passwd_salt))))
	_, err := repo.o.QueryTable("t_platform_balance").
		Filter("Id", p.Id).
		Filter("Balance", oldBalance).
		Filter("Balance2", oldBalance2).
		Update(orm.Params{"Balance": p.Balance, "Balance2": p.Balance2})
	return err
}

func (repo *PayRepo) NewPlatformDetailRecord(p PlatformDetailDto) error {
	if repo.o == nil {
		repo.o = orm.NewOrm()
	}
	_, err := repo.o.Insert(&p)
	return err
}

func (repo *PayRepo) NewWidthDrawRecord(dto WithdrawDto) error {
	if repo.o == nil {
		repo.o = orm.NewOrm()
	}
	dto.Amount2 = fmt.Sprintf("%x", sha1.Sum([]byte(fmt.Sprintf("%d%s", dto.AmountAfterRatio, pay_passwd_salt))))
	_, err := repo.o.Insert(&dto)
	return err
}

func (repo *PayRepo) GetWalletDetailList(memberId, pageNo, pageSize int) (list []WalletDetailDto, cnt int64, err error) {
	o := orm.NewOrm()
	if cnt, err = o.QueryTable("t_wallet_detail").Filter("MemberId", memberId).Count(); err == nil {
		_, err = o.QueryTable("t_wallet_detail").
			Filter("MemberId", memberId).
			OrderBy("-id").
			Limit(pageSize, (pageNo-1)*pageSize).
			All(&list)
	}

	return
}

func (repo *PayRepo) GetWalletWithdrawList(memberId, pageNo, pageSize int) (list []WithdrawDetailDto, cnt int, err error) {
	var num int64
	var flat orm.ParamsList
	o := orm.NewOrm()
	if num, err = o.Raw(SQL_Wallet_Withdraw_List_Count, memberId).ValuesFlat(&flat); num >= 1 && err == nil {
		cnt, err = strconv.Atoi(flat[0].(string))
		_, err = o.Raw(fmt.Sprintf(SQL_Wallet_Withdraw_List, (pageNo-1)*pageSize, pageSize), memberId).QueryRows(&list)
	}

	return
}

func (repo PayRepo) GetBankDetailList(memberId, pageNo, pageSize int) (list []BankDetailDto, cnt int64, err error) {
	o := orm.NewOrm()
	if cnt, err = o.QueryTable("t_bank_detail").Filter("MemberId", memberId).Count(); err == nil {
		_, err = o.QueryTable("t_bank_detail").
			Filter("MemberId", memberId).
			OrderBy("-id").
			Limit(pageSize, (pageNo-1)*pageSize).
			All(&list)
	}

	return
}

func (repo PayRepo) GetTransFLowList(memberId, pageNo, pageSize int) (list []TransFlowDto, cnt int64, err error) {
	o := orm.NewOrm()
	if cnt, err = o.QueryTable("t_trans_flow").Filter("MemberId", memberId).Count(); err == nil {
		_, err = o.QueryTable("t_trans_flow").
			Filter("MemberId", memberId).
			OrderBy("-id").
			Limit(pageSize, (pageNo-1)*pageSize).
			All(&list)
	}

	return
}

func (repo PayRepo) GetBankCard(cardID int) (card BankCardDto, err error) {
	if repo.o == nil {
		repo.o = orm.NewOrm()
	}
	err = repo.o.QueryTable("t_bank_card").
		Filter("Id", cardID).
		One(&card)
	return
}

func (repo PayRepo) GetBankCardList(memberId int) (list []BankCardDto, err error) {
	o := orm.NewOrm()
	_, err = o.QueryTable("t_bank_card").Filter("MemberId", memberId).All(&list)
	return
}

func (repo *PayRepo) NewReward(r RewardDto) (err error) {
	_, err = repo.o.Insert(&r)
	return
}

func (repo *PayRepo) NewOilCardRecord(dto OilCardDto) (err error) {
	if repo.o == nil {
		repo.o = orm.NewOrm()
	}
	dto.Amount2 = fmt.Sprintf("%x", sha1.Sum([]byte(fmt.Sprintf("%d%s", dto.Amount, pay_passwd_salt))))
	_, err = repo.o.Insert(&dto)
	return
}

func (repo PayRepo) GetDefaultOildCardNo(memberId int) (no string) {
	var dto OilCardDto
	o := orm.NewOrm()
	if err := o.QueryTable("t_oilcard").Filter("MemberId", memberId).OrderBy("-id").One(&dto); err == nil {
		no = dto.CardNo
	}
	return
}

func (repo PayRepo) AddOfflinePayInfo(dto PayOfflineDto) error {
	o := orm.NewOrm()
	_, err := o.Insert(&dto)
	return err
}

func (repo PayRepo) GetOfflinePayInfo(waybillID int) (dto PayOfflineDto, err error) {
	o := orm.NewOrm()
	err = o.QueryTable("t_pay_offline").Filter("WaybillID", waybillID).One(&dto)
	return
}

func (repo PayRepo) GetOfflinePayInfoList(memberID int) (list []PayOfflineDto, err error) {
	o := orm.NewOrm()
	_, err = o.QueryTable("t_pay_offline").
		Filter("MemberId", memberID).
		OrderBy("-id").
		Limit(10).
		All(&list)
	return
}

func (repo PayRepo) TryAddOfflineInvoiceInfo(dto InvoiceDto) (int64, error) {
	var id int64
	var temp InvoiceDto

	o := orm.NewOrm()
	err := o.QueryTable("o_invoice").Filter("waybill_id", dto.WaybillId).One(&temp)
	if err != nil {
		id, err = o.Insert(&dto)
	} else {
		id = int64(temp.Id)
	}
	return id, err
}
